<template>
  <div>
    <el-card>
      <el-form :inline="true" style="display: flex; justify-content: space-between">
        <el-form-item label="职位搜索">
          <el-input placeholder="请输入要搜索的职位" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" :disabled="keyword ? false : true" @click="search">搜索</el-button>
          <el-button size="default" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 10px">
      <el-button type="primary" size="default" icon="Plus" @click="addRole">添加职位</el-button>
      <!-- <el-button type="danger" size="default" @click="">批量删除</el-button> -->

      <el-table :data="records" border stripe style="margin-top: 10px">
        <!-- <el-table-column type="selection" width="55px" align="center" /> -->
        <el-table-column type="index" width="55px" align="center" label="#" />
        <el-table-column label="id" align="center" prop="id" />
        <el-table-column label="职位名称" align="center" width="150px" prop="roleName" />
        <el-table-column label="创建时间" align="center" width="150px" prop="createTime" />
        <el-table-column label="更新时间" align="center" width="150px" prop="updateTime" />
        <el-table-column label="操作" align="center" width="300px" fixed="right">
          <template #default="{ row }">
            <el-button v-has="'btn.Role.assgin'" type="primary" size="small" icon="User" @click="setPermisstion(row)">分配权限</el-button>
            <el-button v-has="'btn.Role.update'" type="primary" size="small" icon="Edit" @click="updateRole(row)">编辑</el-button>
            <el-popconfirm :title="`你确定${row.roleName}吗？`" @confirm="deleteRole(row)">
              <template #reference>
                <el-button v-has="'btn.Role.remove'" type="danger" size="small" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]" layout="prev, pager, next, jumper,->, sizes,total" :total="total" background style="margin-top: 10px" @change="getHasRole" />
    </el-card>

    <el-dialog v-model="dialogVisible" :title="RoleParams.id ? '添加职位' : '添加职位'" width="600px">
      <el-form ref="formRef" :rules="rules" :model="RoleParams" label-width="100px">
        <el-form-item label="职位名称" prop="roleName">
          <el-input v-model="RoleParams.roleName" placeholder="请输入角色名称" />
        </el-form-item>
      </el-form>

      <div slot="footer" style="display: flex; justify-content: right">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </el-dialog>

    <el-drawer v-model="drawer" size="350px">
      <template #header>
        <h4>分配权限</h4>
      </template>
      <template #default>
        <el-tree ref="tree" style="max-width: 600px" :data="menuArr" show-checkbox node-key="id" :default-checked-keys="defaultCheckList" :props="defaultProps" default-expand-all />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="">取消</el-button>
          <el-button type="primary" @click="handler">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import useLayOutSettingStore from '@/store/modules/setting';
import { nextTick, onMounted, reactive, ref } from 'vue';
import { reqAddOrUpdateRole, reqAllRole, reqAllPermission, reqSetPermission, reqRemoveRole } from '@/api/acl/role';
import type { RoleResponseData, Records, RoleData, MenuResponseData, MenuDataList, MenuData } from '@/api/acl/role/type';
import { ElMessage } from 'element-plus';

let pageNo = ref<number>(1);
let pageSize = ref<number>(10);
let lastPageSize = ref<number>(10);
let total = ref<number>(400);
let keyword = ref<string>('');

let records = ref<Records>([]);

//树节点配置
const defaultProps = {
  children: 'children',
  label: 'name',
};

//自定义校验规则的回调
const validatorRoleName = (_rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback();
  } else {
    callback(new Error('角色名称长度必须大于2'));
  }
};

//添加编辑校验表单规则
const rules = {
  roleName: [
    {
      required: true,
      trigger: 'blur',
      validator: validatorRoleName,
    },
  ],
};

onMounted(() => {
  getHasRole();
});

const getHasRole = async (num: number = 1) => {
  if (pageSize.value !== lastPageSize.value) {
    pageNo.value = 1;
    lastPageSize.value = pageSize.value;
  } else {
    pageNo.value = num;
  }
  let result: RoleResponseData = await reqAllRole(pageNo.value, pageSize.value, keyword.value);

  if (result.code === 200) {
    total.value = result.data.total;
    records.value = result.data.records;
  }
};
let layOutSettingStore = useLayOutSettingStore();

//搜索按钮回调
const search = async () => {
  getHasRole();
  keyword.value = '';
};

//重置按钮回调
const reset = () => {
  layOutSettingStore.refresh = !layOutSettingStore.refresh;
};

//控制添加角色弹窗
let dialogVisible = ref<boolean>(false);

//角色名称
let RoleParams = reactive<RoleData>({
  roleName: '',
});

//点击添加角色按钮
const addRole = () => {
  dialogVisible.value = true;
  Object.assign(RoleParams, {
    roleName: '',
    id: 0,
  });
  nextTick(() => {
    formRef.value.clearValidate();
  });
};
//点击编辑角色按钮
const updateRole = (row: RoleData) => {
  dialogVisible.value = true;
  Object.assign(RoleParams, row);
  nextTick(() => {
    formRef.value.clearValidate();
  });
};

//获取添加编辑角色表单组件示例
let formRef = ref();
const save = async () => {
  await formRef.value.validate();
  // dialogVisible.value = false;
  let result = await reqAddOrUpdateRole(RoleParams);
  if (result.code === 200) {
    dialogVisible.value = false;
    ElMessage({
      type: 'success',
      message: '操作成功',
    });
    if (!RoleParams.id) {
      pageNo.value = 1;
    }
    getHasRole();
  } else {
    ElMessage({
      type: 'error',
      message: '操作失败',
    });
  }
};

// 控制抽屉与隐藏
const drawer = ref<boolean>(false);

//菜单与按钮权限数据
const menuArr = ref<MenuDataList>([]);

//分配权限按钮的回调
const setPermisstion = async (row: RoleData) => {
  drawer.value = true;
  Object.assign(RoleParams, row);
  let result: MenuResponseData = await reqAllPermission(RoleParams.id as number);
  if (result.code === 200) {
    menuArr.value = result.data;
    selectCheck(result.data);
  }
};

//默认选中的权限
let defaultCheckList = ref<number[]>([]);

//递归遍历选中的权限
const selectCheck = (data: MenuDataList) => {
  data.forEach((item: MenuData) => {
    if (item.children.length !== 0 || item.level !== 4) {
      selectCheck(item.children);
    } else {
      if (item.select) {
        defaultCheckList.value.push(item.id);
      }
    }
  });
};

//树形组件实例
const tree = ref<any>();

//抽屉确认按钮节流阀
let loading = ref<boolean>(false);

//抽屉确定按钮的回调
const handler = async () => {
  if (loading.value) return;
  loading.value = true;
  let arr1 = tree.value.getCheckedKeys();
  let arr2 = tree.value.getHalfCheckedKeys();
  let permissionId = arr1.concat(arr2);

  let result = await reqSetPermission(RoleParams.id as number, permissionId);
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '分配权限成功',
    });
    //页面刷新
    window.location.reload();
  } else {
    ElMessage({
      type: 'error',
      message: '分配权限失败',
    });
  }
  loading.value = false;
};

//删除职位的节流阀
let loading_delete = ref<boolean>(false);
//删除职位的时间回调
const deleteRole = async (row: RoleData) => {
  if (loading_delete.value) return;
  loading_delete.value = true;
  let result = await reqRemoveRole(row.id as number);
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除职位成功',
    });
    if (records.value.length === 1 && pageNo.value !== 1) {
      pageNo.value = pageNo.value - 1;
    }
    getHasRole();
  } else {
    ElMessage({
      type: 'error',
      message: '删除职位失败',
    });
  }
  loading_delete.value = false;
};
</script>

<style lang="scss" scoped></style>
